<?php

/**
 * User: Lomon
 * Date: 2020/12/10
 * 按日统计订单信息
 */
namespace app\admin\command;

use app\admin\model\shopro\goods\Goods;
use app\admin\model\shopro\order\Order;
use app\admin\model\shopro\order\OrderItem;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Exception;
use think\Db;

class ReportOrderDay extends Command
{
    protected function configure()
    {
        $this->setName('ReportOrderDay')->setDescription('按日统计订单信息');
    }
    protected function execute(Input $input, Output $output)
    {
        $output->writeln(date('Y-m-d H:i:s'));
        $output->writeln('start:'.$this->getName());
        /*** 这里写计划任务列表集 START ***/

        //----------------是否在运行--------------//
        $uname = php_uname();
        if(strpos(strtolower($uname),'linux') !== false) {
            $maxnum = 1;//最大线程数
            $n = exec("ps aux |grep '" . $this->getName() . "' | grep -v grep | wc -l");
            if ($n > $maxnum) {
                die(date("Y-m-d H:i:s") . $this->getName() . " is running");
            }
        }

        $rptdate    = date('Y-m-d',strtotime('-1 day'));
        $begin_date = $rptdate ?? '2021-02-21';
        $end_date   = date('Y-m-d');

        //循环天数
        $endnum = (int)((strtotime($end_date) - strtotime($begin_date) ) / 3600 / 24);
        for($i = 0; $i < $endnum; $i++) {

            $rptdate = date('Y-m-d', strtotime($begin_date) + 3600 * 24 * $i);
            //开始统计
            $this->rptByDay($rptdate);
        }
        return ;
    }

    /**
     * 按日统计
     * @param $rptdate '2021-02-01'
     */
    public function rptByDay($rptdate)
    {
        $begin_time = strtotime($rptdate);
        $end_time   = $begin_time + 24 * 3600;

        // 获取昨天的订单
        $orders = Order::where(['createtime'=>['between',[$begin_time,$end_time]],'status'=>['in','1,2']])->select();
        if(empty($orders)){
            return false;
        }

        $orderids = [];
        foreach ($orders as $o){
            $orderids[] = $o['id'];
        }

        //获取昨天的订单明细
        $agent = [];
        $order_items = OrderItem::where(['order_id'=>['in',$orderids]])->select();

        foreach ($order_items as $item){
            //获取该商品的渠道商
            $goods = Goods::find($item['goods_id']);

            $atype = $item['activity_type'] ?? "normal";

            if(empty($agent[$goods['agent_id']][$atype])){
                $data = [
                    'order_ids'         => [$item['order_id']],
                    'user_ids'    		=> [$item['user_id']],
                    'price_cnt'         => $item['goods_price'],
                    'cost_cnt'          => $item['cost_price'],
                    'commission_cnt'    => $item['commission'],
                ];
                $agent[$goods['agent_id']][$atype] = $data;
            }else{
                $orign = $agent[$goods['agent_id']][$atype];

                $orign['order_ids'][]       = $item['order_id'];
                $orign['user_ids'][]  = $item['user_id'];

                $orign['price_cnt']         += $item['goods_price'];
                $orign['cost_cnt']          += $item['cost_price'];
                $orign['commission_cnt']    += $item['commission'];

                $agent[$goods['agent_id']][$atype] = $orign;
            }
        }

        $insdata = [];
        foreach ($agent as $k=>$types){
            foreach ($types as $tname=>$tdata){
                $d = [
                    'date'              => $rptdate,
                    'agent_id'          => $k,
                    'activity_type'     => $tname,
                    'order_cnt'         => count(array_unique($tdata['order_ids'])),
                    'order_person_cnt'  =>count(array_unique($tdata['user_ids'])),
                    'price_cnt'         => $tdata['price_cnt'],
                    'cost_cnt'          => $tdata['cost_cnt'],
                    'commission_cnt'    => $tdata['commission_cnt'],
                ];
                $insdata[] = $d;
            }
        }

        //清空数据
        db('report_order_day')->where(['date'=>$rptdate])->delete();
        //插入数据
        db('report_order_day')->insertAll($insdata);
    }

}